package com.ndp.fb.mq.consumer.account;

import com.alibaba.dubbo.config.annotation.Reference;
import com.ndp.fb.constant.ConfigConst;
import com.ndp.fb.enums.account.AccountOperateType;
import com.ndp.fb.model.fbagent.param.ApiCallBackTarget;
import com.ndp.fb.mq.api.producer.AssetsAlertProducerService;
import com.ndp.fb.mq.api.service.schedulerservice.business.syncbusiness.SyncAccountResourceService;
import com.ndp.fb.mq.consumer.AbstractPullConsumer;
import com.ndp.fb.mq.service.schedulerservice.business.FetchCustomaudiencesService;
import com.ndp.fb.rdb.api.AccountOperateHistoryRdbService;
import com.ndp.fb.rdb.api.CustomAudienceRdbService;
import com.ndp.fb.rdb.api.CustomAudienceTemplateRdbService;
import com.ndp.fb.rdb.api.EntrustAccountRdbService;
import com.ndp.fb.rdb.model.AccountOperateHistory;
import com.ndp.fb.rdb.model.EntrustAccount;
import com.ndp.fb.rdb.model.customaudience.CustomAudienceItem;
import com.ndp.fb.rdb.model.customaudience.CustomAudienceTemplateAndConnectionObject;
import com.ndp.fb.util.ListUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * Created by elvisxiong on 16/1/22.
 */
@Component
public class AssetsConsumerImpl extends AbstractPullConsumer  {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Reference
    private SyncAccountResourceService syncAccountResourceService;

    @Autowired
    private AssetsAlertProducerService assetsAlertProducerService;

    @Reference
    private CustomAudienceTemplateRdbService customAudienceTemplateRdbService;

    @Reference
    private CustomAudienceRdbService customAudienceRdbService;

    @Autowired
    private FetchCustomaudiencesService fetchCustomaudiencesService;

    @Reference
    private EntrustAccountRdbService entrustAccountRdbService;

    @Reference
    private AccountOperateHistoryRdbService accountOperateHistoryRdbService;

    @Override
    public void afterPropertiesSet() throws Exception {
        super.afterPropertiesSet();
    }

    @Override
    public void destroy() throws Exception {
        super.destroy();
    }

    @Override
    protected void consume(String tag, String keys, Object message, Map<String, String> equipment) {
        logger.debug("ConsumerServiceImpl tag >>>> " + tag + " keys >>>" + keys + " message >>> " + message);
        ApiCallBackTarget.AssetsAlert target = (ApiCallBackTarget.AssetsAlert) ApiCallBackTarget.getTargetType(tag);
        String userId = equipment.get("userId");

        Long accountId = equipment.get("accountId")!=null ? Long.parseLong(equipment.get("accountId")):null;
        Long businessId = equipment.get("businessId")!=null ? Long.parseLong(equipment.get("businessId")):null;

        switch (target) {
            case AccountAlert: {
                logger.info("账号变更消息");
                String  accountOperateType = equipment.get("accountOperateType");
                if(accountOperateType != null){
                    if(accountOperateType.equals("ADD")){
                        logger.info("收到账号新增消息,account:{},userId:{}",accountId,userId);
                        syncAccountResourceService.syncCustomaudiences(accountId,userId);
                    }else if(accountOperateType.equals("UPDATE")){
                        logger.info("收到账号更新消息,account:{},userId:{}",accountId,userId);
                        syncAccountResourceService.syncCustomaudiences(accountId,userId);
                    }else if(accountOperateType.equals("DELETE")){
                        logger.info("收到账号删除消息,account:{},userId:{}",accountId,userId);
                        syncAccountResourceService.syncCustomaudiences(accountId,userId);
                        accountDeleteHistorySave(userId, accountId);
                    }else if(accountOperateType.equals("UNBIND")){
                        logger.info("收到账号解绑消息,account:{},userId:{}",accountId,userId);

                        syncAccountResourceService.syncCustomaudiences(accountId,userId);
                    }
                }
            }break;
            case PageAlert:{
                logger.info("page变更消息");
                String pageOperateType = equipment.get("pageOperateType");
                Long pageId = Long.parseLong(equipment.get("pageId"));
                if(pageOperateType.equals("ADD")){
                    logger.info("userId:"+userId+",businessId:"+businessId+",新增page:"+pageId);
                }else if(pageOperateType.equals("UPDATE")){
                    logger.info("userId:"+userId+",businessId:"+businessId+",更新page"+pageId);
                }else if(pageOperateType.equals("DELETE")){
                    logger.info("userId:"+userId+",businessId:"+businessId+",删除page"+pageId);
                }
            }break;
            case AppAlert:{
                logger.info("应用变更信息");
                String appOperateType = equipment.get("entrustConnectionObjectOperateType");
                Long fbConnectionObjectId = equipment.get("fbConnectionObjectId")!=null ? Long.parseLong(equipment.get("fbConnectionObjectId")):null;
                if(appOperateType.equals("ADD")){
                    logger.info("应用下新增账号:"+accountId+"connectionObjectId:" +fbConnectionObjectId);
                    syncCustomAudienceTemplate(accountId, fbConnectionObjectId);
                }else if(appOperateType.equals("DELETE")){
                    logger.info("应用下删除账号:"+accountId +"connectionObjectId:" +fbConnectionObjectId);
                }
            }
            default:
                logger.warn("不识别的消息tag >>>>" + tag + " ; message >>> " + message);
        }
    }

    /**
     * 保存账号操作历史
     * @param userId
     * @param accountId
     */
    private void accountDeleteHistorySave(String userId, Long accountId) {
        AccountOperateHistory accountOperateHistory = new AccountOperateHistory();
        accountOperateHistory.setUserId(userId);
        accountOperateHistory.setAccountOperateType(AccountOperateType.DELETE);
        EntrustAccount entrustAccount = entrustAccountRdbService.findByFbAccountId(accountId);
        if ( entrustAccount.getName() != null && !entrustAccount.getName().equals("")) {
            accountOperateHistory.setAccounts(entrustAccount.getName());
        } else {
            accountOperateHistory.setAccounts(entrustAccount.getFbAccountId().toString());
        }
        accountOperateHistory.setDate(System.currentTimeMillis());
        accountOperateHistoryRdbService.save(accountOperateHistory);
    }

    /**
     * 同步账号和自定义受众模板
     * @param accountId
     * @param fbConnectionObjectId
     */
    private void syncCustomAudienceTemplate(Long accountId, Long fbConnectionObjectId) {
        List<CustomAudienceTemplateAndConnectionObject> customAudienceTemplateList = customAudienceTemplateRdbService.getConnectionObjectByConnectionId(fbConnectionObjectId);
        if (ListUtil.isNotEmpty(customAudienceTemplateList)) {
            for (CustomAudienceTemplateAndConnectionObject item : customAudienceTemplateList) {
                Long customAudienceTemplateId = item.getCustomAudienceTemplateId();
                List<CustomAudienceItem> customAudienceItems = customAudienceRdbService.findByTemplateIdAndAccountId(customAudienceTemplateId,accountId);
                //如果库中没有,就保存账号和模板的关系
                if (customAudienceItems == null || customAudienceItems.size() == 0) {
                    fetchCustomaudiencesService.addCustomaudiences(accountId, customAudienceTemplateId);
                }
            }
        }
    }

    @Override
    public String getTopicName() {
        return ConfigConst.MQ_SERVICES_ACCOUNTALTER_TOPIC;
    }
}
